package com.cqhz.quwan.ui.widget.dialog;


import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cqhz.quwan.R;
import com.cqhz.quwan.model.ESportItemBean;
import com.cqhz.quwan.model.ESportItemSelectBean;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 电竞下单弹出窗口
 * Created by Guojing on 2018/10/22.
 */
public class OrderDialog
{

    private Context                   context;
    private Dialog                    dialog;
    private ViewHolder                holder;
    private ESportItemBean            eSportItemBean;
    private ESportItemSelectBean      eSportItemSelectBean;
    private OrderConfirmClickListener listener;
    private int                       betTimes     = 1;// 投注倍数
    private int                       defaultPay   = 0;// 默认为0
    private double                    bean         = 0.00;// 趣豆余额
    private double                    betNumber    = defaultPay;// 投注数量
    private double                    amountPay    = defaultPay;// 投注额
    private double                    amountProfit = 0.00;// 盈利额

    public OrderDialog(Context context)
    {
        this.context = context;
    }

    public OrderDialog builder()
    {
        // 获取Dialog布局
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_order, null);
        view.setMinimumWidth(10000);// 设置dialog全屏显示

        // 获取自定义Dialog布局中的控件
        holder = new ViewHolder(view);

        holder.actionClose.setOnClickListener(v -> dialog.dismiss());
        holder.actionClosed.setOnClickListener(v -> dialog.dismiss());
        holder.actionGotoRecharge.setOnClickListener(v -> {
            if (listener == null)
            {
                return;
            }

            listener.gotoRecharge();
        });
        holder.actionPayAll.setOnClickListener(v -> {
            holder.radioGroup.check(R.id.action_select1);
            setRadioGroupEnable(false);
            holder.etNumber.setText((int) bean + "");
            betTimes = 1;
            betNumber = bean;
            amountPay = bean;
            setDataChanged();
        });
        holder.actionClean.setOnClickListener(v -> {
            holder.radioGroup.clearCheck();
            setRadioGroupEnable(true);
            holder.etNumber.setText("");
            betTimes = 1;
            betNumber = defaultPay;
            amountPay = defaultPay;
            setDataChanged();
        });
        holder.radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId)
            {
                case R.id.action_select1:
                    betTimes = 1;
                    break;
                case R.id.action_select10:
                    betTimes = 10;
                    break;
                case R.id.action_select50:
                    betTimes = 50;
                    break;
                case R.id.action_select100:
                    betTimes = 100;
                    break;
            }
            setDataChanged();
        });
        // 监听输入事件
        holder.etNumber.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                try
                {
                    int value = Integer.parseInt(s.toString().trim());
                    betNumber = value;
                    if (value <= 0)
                    {
                        betNumber = defaultPay;
                        holder.etNumber.setText(betNumber + "");
                    }
                }
                catch (NumberFormatException e)
                {
                    betNumber = defaultPay;
                }
                setRadioGroupEnable(true);
                setDataChanged();
            }

            @Override
            public void afterTextChanged(Editable s)
            {

            }
        });

        // 定义Dialog布局和参数
        dialog = new Dialog(context, R.style.DialogStyle);
        dialog.setContentView(view);
        holder.llOrderDialog.setLayoutParams(new FrameLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));

        return this;
    }

    /**
     * 设置全选时禁用组选择的方法
     *
     * @param isEnable
     */
    private void setRadioGroupEnable(Boolean isEnable)
    {
        for (int i = 0; i < holder.radioGroup.getChildCount(); i++)
        {
            holder.radioGroup.getChildAt(i).setEnabled(isEnable);
            if (isEnable && i == 0)
            {
                holder.radioGroup.getChildAt(i).setEnabled(true);
            }
        }
    }

    /**
     * 设置投注条件改变时，预估盈利额
     */
    private void setDataChanged()
    {
        amountPay = multiply(betNumber, betTimes);
        amountProfit = multiply(multiply(betNumber, betTimes), Double.parseDouble(eSportItemSelectBean.getPartOdds()) - 1);
        holder.tvAmountPay.setText((int) amountPay + "");
        holder.tvAmountProfit.setText((int) amountProfit + "");
    }

    /**
     * 设置数据
     *
     * @param eSportItemBean
     * @param eSportItemSelectBean
     * @return
     */
    public OrderDialog setData(ESportItemBean eSportItemBean, ESportItemSelectBean eSportItemSelectBean)
    {
        this.eSportItemBean = eSportItemBean;
        this.eSportItemSelectBean = eSportItemSelectBean;

        holder.tvName.setText(eSportItemSelectBean.getPartName());
        holder.tvOdds.setText("@" + eSportItemSelectBean.getPartOdds());
        setDataChanged();
        return this;
    }

    /**
     * 设置数据
     *
     * @param pageTitle
     * @return
     */
    public OrderDialog setPageTitle(String pageTitle)
    {
        holder.tvPlayDescribe.setText(pageTitle + " " + eSportItemBean.getPlayDescribe());
        return this;
    }

    /**
     * 设置数据
     *
     * @param bean
     * @return
     */
    public OrderDialog setBean(String bean)
    {
        this.bean = Double.parseDouble(bean);
        holder.actionGotoRecharge.setText(bean);
        return this;
    }

    /**
     * 设置回调事件
     *
     * @param listener
     * @return
     */
    public OrderDialog setListener(@NonNull final OrderConfirmClickListener listener)
    {
        this.listener = listener;
        return this;
    }

    /**
     * 设置按钮文字和事件
     *
     * @param text
     * @return
     */
    public OrderDialog setActionConfirm(@NonNull CharSequence text)
    {
        holder.actionConfirm.setText("".equals(text) ? "预测" : text);
        holder.actionConfirm.setOnClickListener(v -> {
            if (listener == null)
            {
                return;
            }
            String betNumber = holder.etNumber.getText().toString().trim();
            if (betNumber.isEmpty())
            {
                listener.showTips("请输入投注数量");
                return;
            }

            if (amountPay > bean)
            {
                listener.showDialog();
                return;
            }

            listener.onOrderConfirmClick(eSportItemBean, eSportItemSelectBean.getPosition(), ((int) amountPay) + "");
        });
        return this;
    }

    /**
     * 显示
     */
    public void show()
    {
        dialog.setCancelable(false);
        if (!dialog.isShowing())
        {
            dialog.show();
        }
    }

    /**
     * 取消
     */
    public void dismiss()
    {
        if (dialog.isShowing())
        {
            dialog.dismiss();
        }
    }

    /**
     * 提取字符串中的数字，整数、double、负数都可以
     */
    String getNumber(String str)
    {
        // 保存负号
        String numFlag = "";
        if (str.contains("-"))
        {
            numFlag = "-";
        }
        // 控制正则表达式的匹配行为的参数(小数)
        Pattern p = Pattern.compile("(\\d+\\.\\d+)");
        // Matcher类的构造方法也是私有的,不能随意创建,只能通过Pattern.matcher(CharSequence input)方法得到该类的实例.
        Matcher m = p.matcher(str);
        // m.find用来判断该字符串中是否含有与"(\\d+\\.\\d+)"相匹配的子串
        if (m.find())
        {
            // 如果有相匹配的,则判断是否为null操作
            // group()中的参数：0表示匹配整个正则，1表示匹配第一个括号的正则,2表示匹配第二个正则,在这只有一个括号,即1和0是一样的
            str = m.group(1) == null ? "" : m.group(1);
        }
        else
        {
            // 如果匹配不到小数，就进行整数匹配
            p = Pattern.compile("(\\d+)");
            m = p.matcher(str);
            if (m.find())
            {
                // 如果有整数相匹配
                str = m.group(1) == null ? "" : m.group(1);
            }
            else
            {
                // 如果没有小数和整数相匹配,即字符串中没有整数和小数，就设为空
                str = "";
            }
        }
        return numFlag + str;
    }

    /**
     * 提供精确的乘法运算。
     *
     * @param v1
     * @param v2
     * @return 两个参数的积
     */
    double multiply(double v1, double v2)
    {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).setScale(2, RoundingMode.HALF_UP).doubleValue();
    }

    public interface OrderConfirmClickListener
    {
        /**
         * 当提交投注数量为空时，调用
         */
        void showTips(String tips);

        /**
         * 当提交投注数量余额不足时，调用
         */
        void showDialog();

        /**
         * 去充值
         */
        void gotoRecharge();

        /**
         * 点击提交订单
         */
        void onOrderConfirmClick(@NonNull ESportItemBean bean, @NonNull String teamValue, @NonNull String payAmount);
    }

    static class ViewHolder
    {
        View         actionClosed;
        ImageView    actionClose;
        TextView     actionGotoRecharge;
        TextView     tvPlayDescribe;
        TextView     tvName;
        TextView     tvOdds;
        EditText     etNumber;
        TextView     actionPayAll;
        RadioButton  actionSelect1;
        RadioButton  actionSelect10;
        RadioButton  actionSelect50;
        RadioButton  actionSelect100;
        RadioGroup   radioGroup;
        LinearLayout actionClean;
        TextView     tvAmountPay;
        TextView     tvAmountProfit;
        TextView     actionConfirm;
        LinearLayout llOrderDialog;

        ViewHolder(View view)
        {
            actionClosed = view.findViewById(R.id.action_closed);
            actionClose = view.findViewById(R.id.action_close);
            actionGotoRecharge = view.findViewById(R.id.action_goto_recharge);
            tvPlayDescribe = view.findViewById(R.id.tv_play_describe);
            tvName = view.findViewById(R.id.tv_name);
            tvOdds = view.findViewById(R.id.tv_odds);
            etNumber = view.findViewById(R.id.et_number);
            actionPayAll = view.findViewById(R.id.action_pay_all);
            actionSelect1 = view.findViewById(R.id.action_select1);
            actionSelect10 = view.findViewById(R.id.action_select10);
            actionSelect50 = view.findViewById(R.id.action_select50);
            actionSelect100 = view.findViewById(R.id.action_select100);
            radioGroup = view.findViewById(R.id.radioGroup);
            actionClean = view.findViewById(R.id.action_clean);
            tvAmountPay = view.findViewById(R.id.tv_amount_pay);
            tvAmountProfit = view.findViewById(R.id.tv_amount_profit);
            actionConfirm = view.findViewById(R.id.action_confirm);
            llOrderDialog = view.findViewById(R.id.ll_order_dialog);
        }
    }
}
